package com.info.zhiduoduo.core.service.payment.thirdpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.info.zhiduoduo.alipay.service.AliPayApiService;
import com.info.zhiduoduo.common.configs.*;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.exception.RollbackException;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.core.dto.alipay.AlipayTransferFormBean;
import com.info.zhiduoduo.core.dto.alipay.AlipayTransferQueryFormBean;
import com.info.zhiduoduo.core.service.CoreMakerAlipayService;
import com.info.zhiduoduo.core.service.WxMessageService;
import com.info.zhiduoduo.core.service.ZhiduoduoProjectService;
import com.info.zhiduoduo.repository.entity.order.TradeRecord;
import com.info.zhiduoduo.repository.mapper.maker.MakerAlipayPrincipalOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class AliPayService implements ThirdPayService {

    @Autowired
    ZhiduoduoProjectService zhiduoduoProjectService;
    @Autowired
    WxMessageService wxMessageService;
    @Autowired
    CoreMakerAlipayService coreMakerAlipayService;
    @Autowired
    AliPayApiService aliPayApiService;

    @Resource
    MakerAlipayPrincipalOrderMapper makerAlipayPrincipalOrderMapper;

    @Autowired
    CommonConfig commonConfig;
    @Autowired
    ZddUrlConfig zddUrlConfig;
    @Autowired
    PayConfig payConfig;
    @Autowired
    PayTestModeConfig payTestModeConfig;

    @Override
    public SmartResult doCallPayApi(TradeRecord tradeRecord) {
        SmartResult smartResult = null;
        // 测试
//		if (payTestModeConfig.isTestMode()) {
//			// 直接支付成功
//			// 等待30秒，模拟超时情况
//			try {
//				Thread.sleep(30000);
//			} catch (InterruptedException e) {
//			}
//			return handlePayUserTradeState(tradeRecord, ZhaoShangPayOrderState.SUCCESS, "", "");
//		} else {
        //调用第三方支付
        AlipayTransferFormBean formBean = AlipayTransferFormBean.of(tradeRecord);
        String url = zddUrlConfig.getBasePayUrl() + payConfig.getAliPayTransferUrl();
        LogUtil.info("支付宝转账支付调用 url = " + url);
        smartResult = new RestTemplate().postForObject(url, formBean, SmartResult.class);
//		}
        return handleAliPayTransferResult(tradeRecord, smartResult);
    }

    @Override
    public SmartResult handlePayUserTradeState(TradeRecord trade, String orderState, String errorcode, String errormsg) {
        return SmartResult.fail(StatusMsg.StatusMsg_445);
    }

    public void queryTradeResult(TradeRecord trade) {
        AlipayTransferQueryFormBean formBean = AlipayTransferQueryFormBean.of(trade);
        SmartResult smartResult = new RestTemplate().postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getAliPayTransferQueryUrl(),
                formBean, SmartResult.class);
        if (smartResult.getObject() != null && smartResult.isSuccessful()) {
            AlipayFundTransCommonQueryResponse payResult = JSON.parseObject(JSON.toJSONString(smartResult.getObject()),
                    new TypeReference<AlipayFundTransCommonQueryResponse>() {
                    });
            handlePayUserTradeState(trade, payResult);
        }

    }

    public SmartResult handlePayUserTradeState(TradeRecord trade, AlipayFundTransCommonQueryResponse payResult) {
        if (trade == null || null == payResult) return SmartResult.success(StatusMsg.StatusMsg_444);
        trade.setErrorcode(payResult.getCode()).setErrormsg(payResult.getMsg());
        if (payResult.isSuccess()) {
            trade.setTradestate(Constants.TRADE_SUCCESS).setFinishtime(new Date());
            zhiduoduoProjectService.doAfterPayUserTradeSucceed(trade);
        } else {
            trade.setErrorcode(payResult.getCode()).setErrormsg(payResult.getSubMsg());
            trade.setTradestate(Constants.TRADE_FAIL).setFinishtime(new Date());
            wxMessageService.notifyAdminPaymentFail(trade);
        }
        if (trade.updateById()) return SmartResult.success();
        return SmartResult.fail(StatusMsg.StatusMsg_445);
    }

    private SmartResult handleAliPayTransferResult(TradeRecord trade, SmartResult smartResult) {
        if (null == smartResult) {
            LogUtil.info("zdd-pay没有返回smartResult");
            throw new RollbackException(" 项目,支付宝支付失败");
        }
        if (smartResult.getObject() == null || smartResult.isFailed()) {
            if (smartResult.getState() == StatusMsg.StatusMsg_446.state) {
                LogUtil.info("支付宝网络问题，将项目状态修改为进行中，等待后续查询结果");
                //招商银行网络错误 发送通知
                wxMessageService.tradeNetErrorNotifyAdmin();
                trade.setTradestate(Constants.TRADE_IN_PROCESS);
                if (trade.updateById()) return SmartResult.success();
            }
            // 返回 其他请求结果报错
            return SmartResult.fail(StatusMsg.StatusMsg_445);
        } else {
            //支付接口调用成功,查看交易结果
            AlipayFundTransUniTransferResponse payResult = JSON.parseObject(JSON.toJSONString(smartResult.getObject()), new TypeReference<AlipayFundTransUniTransferResponse>() {
            });
            if (payResult.isSuccess()) {
                trade.setPartnerOrderNo(payResult.getOutBizNo()).setTradestate(Constants.TRADE_IN_PROCESS);
                if (trade.updateById()) return SmartResult.success();
                return SmartResult.fail(StatusMsg.StatusMsg_445);
            } else {
                trade.setTradestate(Constants.TRADE_FAIL).setFinishtime(new Date());
                wxMessageService.notifyAdminPaymentFail(trade);
                if (trade.updateById()) return SmartResult.success();
                return SmartResult.fail(StatusMsg.StatusMsg_445);
            }
        }
    }

    @Override
    public SmartResult handlePayJiugeTradeState(TradeRecord trade, String orderState, String errorcode, String errormsg) {
        return SmartResult.fail(StatusMsg.StatusMsg_445);
    }

}
